<template>
  <div class="interface-square">
    <div class="header">
      <h2>接口广场</h2>
      <p>发现和调用各种实用的API接口</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchParams.searchText"
        placeholder="搜索接口名字"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <!-- 排序选择器 -->
      <el-select
        v-model="searchParams.sortBy"
        placeholder="排序方式"
        style="width: 150px"
        @change="handleSortChange"
      >
        <el-option label="创建时间" value="createTime" />
        <el-option label="调用次数" value="invokeCount" />
        <el-option label="接口名称" value="name" />
      </el-select>
      
      <el-select
        v-model="searchParams.sortOrder"
        placeholder="排序"
        style="width: 100px"
        @change="handleSortChange"
      >
        <el-option label="降序" value="desc" />
        <el-option label="升序" value="asc" />
      </el-select>
      
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
    </div>

    <!-- 接口列表 -->
    <div class="interface-list">
      <el-row :gutter="16">
        <el-col 
          v-for="item in interfaceList" 
          :key="item.id" 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6"
        >
          <el-card class="interface-card" shadow="hover">
            <div class="card-header">
              <h3 class="interface-name">{{ item.name }}</h3>
              <el-tag 
                :type="getMethodTagType(item.method)" 
                size="small"
              >
                {{ item.method }}
              </el-tag>
            </div>
            <p class="interface-description">{{ item.description }}</p>
            
            <!-- 调用次数显示 -->
            <div class="interface-stats">
              <div class="stat-item">
                <el-icon class="stat-icon"><TrendCharts /></el-icon>
                <span class="stat-label">调用次数:</span>
                <span class="stat-value">{{ getInvokeCount(item) }}</span>
              </div>
            </div>
            
            <div class="card-footer">
              <el-button 
                type="primary" 
                size="small" 
                @click="showDetail(item)"
              >
                查看详情
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="showInvoke(item)"
              >
                在线调用
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="searchParams.current"
        v-model:page-size="searchParams.pageSize"
        :page-sizes="[8, 16, 24, 32]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-loading />
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && interfaceList.length === 0" class="empty">
      <el-empty description="暂无接口数据" />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="接口详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentInterface" class="detail-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="接口名称">
            {{ currentInterface.name }}
          </el-descriptions-item>
          <el-descriptions-item label="接口描述">
            {{ currentInterface.description }}
          </el-descriptions-item>
          <el-descriptions-item label="请求方法">
            <el-tag :type="getMethodTagType(currentInterface.method)">
              {{ currentInterface.method }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="接口地址">
            {{ currentInterface.url }}
          </el-descriptions-item>
          <el-descriptions-item label="调用次数">
            <el-tag type="info">{{ getInvokeCount(currentInterface) }} 次</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请求参数">
            <pre>{{ formatJson(currentInterface.requestParams) || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="请求头">
            <pre>{{ currentInterface.requestHeader || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="响应头">
            <pre>{{ currentInterface.responseHeader || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="响应结果示例">
            <pre>{{ formatJson(currentInterface.responseResult) || '无' }}</pre>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(currentInterface.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatTime(currentInterface.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentInterface.status === 1 ? 'success' : 'danger'">
              {{ currentInterface.status === 1 ? '上线' : '下线' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 调用对话框 -->
    <el-dialog
      v-model="invokeVisible"
      title="在线调用"
      width="800px"
      :before-close="handleInvokeClose"
    >
      <div v-if="currentInterface" class="invoke-content">
        <el-form :model="invokeForm" label-width="100px">
          <el-form-item label="接口名称">
            <span>{{ currentInterface.name }}</span>
          </el-form-item>
          <el-form-item label="请求方法">
            <el-tag :type="getMethodTagType(currentInterface.method)">
              {{ currentInterface.method }}
            </el-tag>
          </el-form-item>
          <el-form-item label="接口地址">
            <span>{{ currentInterface.url }}</span>
          </el-form-item>
          <el-form-item label="调用次数">
            <el-tag type="info">{{ getInvokeCount(currentInterface) }} 次</el-tag>
          </el-form-item>
          <el-form-item 
            v-if="currentInterface.requestParams" 
            label="请求参数"
          >
            <el-input
              v-model="invokeForm.requestParams"
              type="textarea"
              :rows="4"
              placeholder="请输入请求参数 (JSON格式)"
            />
          </el-form-item>
        </el-form>
        
        <div class="invoke-actions">
          <el-button type="primary" @click="handleInvoke" :loading="invoking">
            发送请求
          </el-button>
          <el-button @click="handleInvokeClose">取消</el-button>
        </div>

        <div v-if="invokeResult" class="invoke-result">
          <h4>调用结果：</h4>
          <el-input
            :model-value="invokeResult"
            type="textarea"
            :rows="6"
            readonly
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, TrendCharts } from '@element-plus/icons-vue'
import { listInterfaceInfoUsingGET, invokeInterfaceInfoUsingPOST } from '@/api/interfaceInfo'

// 响应式数据
const interfaceList = ref([])
const loading = ref(false)
const total = ref(0)
const detailVisible = ref(false)
const invokeVisible = ref(false)
const currentInterface = ref(null)
const invoking = ref(false)
const invokeResult = ref('')

// 搜索参数
const searchParams = reactive({
  current: 1,
  pageSize: 16,
  searchText: '',
  sortBy: 'createTime', // 默认按创建时间排序
  sortOrder: 'desc' // 默认降序
})

// 调用表单
const invokeForm = reactive({
  requestParams: ''
})

// 获取接口调用次数
const getInvokeCount = (interfaceItem) => {
  return interfaceItem?.interfaceStatis?.invokeCount || 0
}

// 前端排序函数
const sortInterfaceList = (list) => {
  if (!list || list.length === 0) return list
  
  const sortedList = [...list]
  
  sortedList.sort((a, b) => {
    let aValue, bValue
    
    switch (searchParams.sortBy) {
      case 'invokeCount':
        aValue = getInvokeCount(a)
        bValue = getInvokeCount(b)
        break
      case 'name':
        aValue = a.name || ''
        bValue = b.name || ''
        break
      case 'createTime':
      default:
        aValue = new Date(a.createTime || 0).getTime()
        bValue = new Date(b.createTime || 0).getTime()
        break
    }
    
    // 处理字符串和数字比较
    if (typeof aValue === 'string' && typeof bValue === 'string') {
      aValue = aValue.toLowerCase()
      bValue = bValue.toLowerCase()
    }
    
    if (searchParams.sortOrder === 'asc') {
      return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
    } else {
      return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
    }
  })
  
  return sortedList
}

// 获取接口列表
const getInterfaceList = async () => {
  loading.value = true
  try {
    const params = {
      current: searchParams.current,
      pageSize: searchParams.pageSize,
      name: searchParams.searchText || undefined,
      description: searchParams.searchText || undefined
    }
    const response = await listInterfaceInfoUsingGET(params)
    console.log('接口列表响应:', response)
    
    let records = response.data?.records || []
    
    // 前端排序
    records = sortInterfaceList(records)
    
    interfaceList.value = records
    total.value = response.data?.total || 0
  } catch (error) {
    console.error('获取接口列表失败:', error)
    ElMessage.error('获取接口列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchParams.current = 1
  getInterfaceList()
}

// 重置
const handleReset = () => {
  searchParams.current = 1
  searchParams.searchText = ''
  searchParams.sortBy = 'createTime'
  searchParams.sortOrder = 'desc'
  getInterfaceList()
}

// 排序变化处理
const handleSortChange = () => {
  searchParams.current = 1
  getInterfaceList()
}

// 分页处理
const handleSizeChange = (size) => {
  searchParams.pageSize = size
  searchParams.current = 1
  getInterfaceList()
}

const handleCurrentChange = (page) => {
  searchParams.current = page
  getInterfaceList()
}

// 显示详情
const showDetail = (item) => {
  currentInterface.value = item
  detailVisible.value = true
}

// 关闭详情
const handleDetailClose = () => {
  detailVisible.value = false
  currentInterface.value = null
}

// 显示调用
const showInvoke = (item) => {
  currentInterface.value = item
  invokeForm.requestParams = ''
  invokeResult.value = ''
  invokeVisible.value = true
}

// 关闭调用
const handleInvokeClose = () => {
  invokeVisible.value = false
  currentInterface.value = null
  invokeForm.requestParams = ''
  invokeResult.value = ''
}

// 执行调用
const handleInvoke = async () => {
  if (!currentInterface.value) return
  
  invoking.value = true
  try {
    const params = {
      id: currentInterface.value.id,
      userRequestParams: invokeForm.requestParams || undefined
    }
    const response = await invokeInterfaceInfoUsingPOST(params)
    console.log('调用响应:', response)
    invokeResult.value = JSON.stringify(response.data || response, null, 2)
    ElMessage.success('调用成功')
    
    // 调用成功后刷新列表以更新调用次数
    getInterfaceList()
  } catch (error) {
    console.error('调用失败:', error)
    ElMessage.error('调用失败: ' + (error.message || '未知错误'))
    invokeResult.value = JSON.stringify(error, null, 2)
  } finally {
    invoking.value = false
  }
}

// 获取方法标签类型
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 格式化JSON字符串
const formatJson = (jsonString) => {
  if (!jsonString) return null
  try {
    const parsed = JSON.parse(jsonString)
    return JSON.stringify(parsed, null, 2)
  } catch (error) {
    // 如果不是有效的JSON，直接返回原字符串
    return jsonString
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  getInterfaceList()
})
</script>

<style scoped>
.interface-square {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.header p {
  color: #909399;
  font-size: 14px;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.interface-list {
  margin-bottom: 24px;
}

.interface-card {
  height: 100%;
  transition: all 0.3s;
}

.interface-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.interface-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 8px;
}

.interface-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.interface-stats {
  margin-bottom: 16px;
  padding: 8px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #666;
}

.stat-icon {
  margin-right: 4px;
  color: #409eff;
}

.stat-label {
  margin-right: 4px;
}

.stat-value {
  font-weight: 600;
  color: #409eff;
}

.card-footer {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.loading {
  text-align: center;
  padding: 40px;
}

.empty {
  text-align: center;
  padding: 40px;
}

.detail-content pre {
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}

.invoke-content {
  padding: 20px 0;
}

.invoke-actions {
  margin: 20px 0;
  text-align: center;
}

.invoke-result {
  margin-top: 20px;
}

.invoke-result h4 {
  margin-bottom: 12px;
  color: #303133;
}

@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    max-width: none;
  }
  
  .card-footer {
    flex-direction: column;
  }
}
</style>
